package com.example.dddsample.gateway.config;

import com.example.dddsample.gateway.Coder.MyDecoder;
import com.example.dddsample.gateway.Coder.MyEncoder;
import com.example.dddsample.gateway.Interceptor.FeignBasicAuthRequestInterceptor;
import feign.Client;
import feign.Logger;
import feign.Request;
import feign.Retryer;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.okhttp.OkHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: bebm
 * @date: 2022/4/1 8:29
 * @description:
 */
@Configuration
public class FeignConfiguration {

    //todo 重写重试策略，超时策略，日志等配置
    /*Logger.Level：日志级别
    Retryer: 重试机制
    Request.Options:条件　请求超时，响应
    RequestInterceptor：请求拦截器*/

    /**
     * OpenFeign 日志增强
     * 配置 OpenFeign 记录哪些内容
     */
    @Bean
    Logger.Level feginLoggerLevel() {
        return Logger.Level.FULL;
    }

    /**
     * 重试机制
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public Retryer feignRetryer() {
         // return Retryer.NEVER_RETRY;
        //不重试
        // return Retryer.NEVER_RETRY;
        // period=100 发起当前请求的时间间隔
        // maxPeriod=1000 发起当前请求的最大时间间隔
        // maxAttempts=2 重试次数是1，因为包括第一次
        Retryer retryer = new Retryer.Default(100, 300, 2);
        return retryer;
    }

    /**
     * Options 的第一个参数是连接超时时间（ms）第二个是取超时时间（ms）
     * @return
     */
    @Bean
    public Request.Options options() {
        return new Request.Options(10000, 5000);
    }

    /**
     * 拦截期可以进行权限控制
     * @return
     */
    @Bean
    public FeignBasicAuthRequestInterceptor basicAuthRequestInterceptor() {
        return new FeignBasicAuthRequestInterceptor();
    }

    /**
     * 启用okHttpClient方式
     */
    @Autowired(required = false)
    private okhttp3.OkHttpClient okHttpClient;
    @Bean
    @ConditionalOnMissingBean(Client.class)
    public Client feignClient() {
        if (this.okHttpClient != null) {
            return new OkHttpClient(this.okHttpClient);
        }
        return new OkHttpClient();
    }

    /**
     * 解码
     * @return
     */
    @Bean
    public Decoder decoder() {
        //xml,mgson,
        return new MyDecoder();
    }

    /**
     * 编码
     * @return
     */
    @Bean
    public Encoder encoder() {
        //text,xml,mgson,
        return new MyEncoder();
    }


}
